#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
手动修复快乐8历史数据排序的脚本
"""

import csv
import os

def manual_fix():
    # 文件路径
    file_path = os.path.join(os.path.dirname(__file__), 'kl8_history.csv')
    backup_path = file_path + '.backup'
    
    print("读取数据...")
    # 读取所有数据
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    print(f"总行数: {len(lines)}")
    
    # 分离表头和数据
    header = lines[0]
    data_lines = lines[1:]
    
    print(f"表头: {header.strip()}")
    print(f"数据行数: {len(data_lines)}")
    
    # 解析数据并按日期排序
    parsed_data = []
    for line in data_lines:
        parts = line.strip().split(',')
        if len(parts) >= 22:
            # 期号, 日期, 20个号码
            issue = parts[0]
            date = parts[1]
            numbers = parts[2:22]
            parsed_data.append((issue, date, numbers, line))
    
    print(f"解析的数据行数: {len(parsed_data)}")
    
    # 按日期排序
    parsed_data.sort(key=lambda x: x[1])  # 按日期排序
    
    print("创建备份...")
    # 创建备份
    os.rename(file_path, backup_path)
    
    print("写入排序后的数据...")
    # 写入排序后的数据
    with open(file_path, 'w', encoding='utf-8', newline='') as f:
        f.write(header)  # 写入表头
        for item in parsed_data:
            f.write(item[3])  # 写入原始行
    
    print("修复完成!")

if __name__ == "__main__":
    manual_fix()